package stack_queue.stack;

import java.util.Arrays;
import java.util.NoSuchElementException;

/**
 * @Author: wenjingyuan
 * @Date: 2022/09/28/15:45
 * @Description:基于数组实现的顺序栈
 */
public class Stack<E> {
    private E[] elementData;
    //当前栈中的元素个数
    private int size;
    public Stack(){
        //int[] data=new int[10];
        elementData= (E[]) new Object[3];
    }
    public Stack(int initCap){
        elementData= (E[]) new Object[initCap];
    }
    //入栈操作
    public void push(E value){
        //扩容
        if(size==elementData.length){
            elementData= Arrays.copyOf(elementData,2*elementData.length);
        }
        elementData[size]=value;
        size++;
    }
    //出栈操作
    public E pop(){
        if(getSize()==0){
         //当前栈为空
         throw new NoSuchElementException("栈为空");
        }
        E olaValue=elementData[size-1];
        size--;
        elementData[size]=null;
        return olaValue;
    }
    //查看栈顶元素，不出栈
    public E peek(){
        if(getSize()==0){
            //当前栈为空
            throw new NoSuchElementException("栈为空");
        }
        return elementData[size-1];
    }
    private int  getSize() {
        return size;
    }
    //输出

    @Override
    public String toString() {
       StringBuilder sb=new StringBuilder();
       sb.append('[');
       for(int i = 0; i < size; i++){
           sb.append(elementData[i]);
           if(i!=size-1){
               sb.append(',');
           }
       }
       sb.append(']');
       return sb.toString();
    }
}
